package longfly.development;

import java.util.ArrayList;
import java.util.List;

import longfly.development.R.id;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Table_ZhuanTai extends Activity {
	
	TextView	ALL_TABLE;
	TextView	ALL_FREE_TABLE;
	GridView	GRIDVIEW_TABLE;
	Button		FRONTPAGE;
	Button		NEXTPAGE;
	TextView	NOWPAGE;
	TextView	ALLPAGE;

	/********对话框内控件***************/
	Button DAILOG_BTN_SURE;	
	Button DAILOG_BTN_CANCEL;
	TextView	DAILOG_TEXT_TABLE_NUM,DAILOG_TEXT_TABLE_OLD_NUM,DAILOG_TEXT_TABLE_SELLNUM;
	/********对话框内控件***************/
	
	
	Button			FIND_TABLE_NUM;
	
	private	int Dispay_widthPixels;
   	private int DIALOG_FIND=101;

	private List<Grid_Item_Table> mylist;
	private	GridItemTableSQLAdapter	adapterr;
	SQLiteDatabase db;
	String	UserLimit;
	String	UserCode;
	String  num;
	String Share_Table_SELLNum ,Share_Table_Num,NEW_Table_Num;	//上一页传来的开台单号
    private final int UPDATE_UI = 1;

    Handler mHandler; 
    int nowpage = 1;
    boolean ref_if = true;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		DisplayMetrics displaysMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics( displaysMetrics );
        Dispay_widthPixels=displaysMetrics.widthPixels;	//以上是初始化一个UI像素的描述！
        long	startTime =	Debug.threadCpuTimeNanos(); 
		switch (Dispay_widthPixels) {	//根据屏幕的横向像素来加载不通的UI界面！
			case 800:
		        setContentView(R.layout.i800_table_zhuantai);
		        break;
			case 1024:
		        setContentView(R.layout.i800_table_zhuantai);
				break;
			default:
				break;
		}          
        long	endXMLTime =	Debug.threadCpuTimeNanos(); 
		Log.i("info", "执行setContentView(R.layout.i800_table)用时"+(endXMLTime - startTime) +"纳秒");  
		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);

		find_id();
        key_things();
        init_grid(1);
        Refresh_State();
        init_data();		//初始化从上一页获取的导入数据
        
        //启动刷新桌台的线程
        mHandler = new MyHandler();//创建Handler 
        time_ref.start();

        long	endLoadTime =	Debug.threadCpuTimeNanos(); 
		Log.i("info", "载入数据用时"+(endLoadTime - endXMLTime) +"纳秒");  
    }
 
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
        init_grid(nowpage);
        Refresh_State();   
        ref_if = true;
        System.out.println("onResume");
    }

    /********************定时刷新桌台的线程开启*********************************************/
	MyThread time_ref = new MyThread();		//接收PC端数据的线程

	//接收PC端数据的线程
	class MyThread extends Thread 
	{  

		public void run() 
		{
			Time_Ref();
		}
	}   
    

	private void Time_Ref() {
		// TODO Auto-generated method stub
		for(;;)
		{
			try {
				Thread.sleep(1000);
		    	if(ref_if)
		    	{
	                //UPDATE是一个自己定义的整数，代表了消息ID 
	                Message msg = mHandler.obtainMessage(UPDATE_UI); 
	                mHandler.sendMessage(msg); 
	                System.out.println(" ref_if = true");
		    	}
		    	else{
		            System.out.println(" ref_if = flash");
		    	}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 			
		}	
	}	
	
    private class MyHandler extends Handler 
    {

        @Override 
        public void handleMessage(Message msg) { 
            // TODO Auto-generated method stub 
            super.handleMessage(msg); 
            switch(msg.what) 
            { 
	            case UPDATE_UI://在收到消息时，对界面进行更新 	            	
	                init_grid(nowpage);
	                Refresh_State();   
	                break; 
            } 
        } 
    }
    /********************定时刷新桌台的线程结束*********************************************/

    //获取前一张台的桌号和开台单号
    private void init_data() {
		// TODO Auto-generated method stub
		Bundle bundle=getIntent().getExtras();
		  //获取Bundle的信息
		try {
			Share_Table_Num 	=  bundle.getString("table_number");
			Share_Table_SELLNum =  bundle.getString("sell_number");			
		} catch (Exception e) {
			// TODO: handle exception
			Share_Table_Num 	=  null;
			Share_Table_SELLNum =  null;
		}

	}
	
    //刷新桌面的空闲台数
	private void Refresh_State() {
		// TODO Auto-generated method stub
		int	All_Table=0,Free_Table=0;
		String[]	Sql_String_condition = { "1" };	

//		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);
		//查全部的桌台
		try {
    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tableinf", null);
			while (cursor.moveToNext()) {
				All_Table ++;
			}
			ALL_TABLE.setText(""+All_Table);
			cursor.close();
		} catch (Exception e) {
			ALL_TABLE.setText("");
		}	

		//空闲部的桌台
		try {
    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tableinf where iTableState = ?", Sql_String_condition);
			while (cursor.moveToNext()) {
				Free_Table ++;
			}
			ALL_FREE_TABLE.setText(""+Free_Table);
			cursor.close();
		} catch (Exception e) {
			ALL_FREE_TABLE.setText("");
		}
		
	}

	//刷新指定分页的桌台网格控件
	private void init_grid( int pageID ) {
		// TODO Auto-generated method stub
		// 用于初始化
		mylist = new ArrayList<Grid_Item_Table>();
		String TABLE_NAME = "lfcy_base_tableinf";
		int PageSize = 30 ;
		String sql= "select * from " + TABLE_NAME +     
        " Limit "+String.valueOf(PageSize)+ " Offset " +String.valueOf( (pageID-1)*PageSize); 
		try {
    		Cursor  cursor = db.rawQuery( sql, null);
			while (cursor.moveToNext()) {
				Grid_Item_Table picture = new Grid_Item_Table();
				picture.setImageId(cursor.getInt(cursor
						.getColumnIndex("iTableState")));
				picture.setTableState(cursor.getString(cursor
						.getColumnIndex("iTableState")));	//桌台的状态（空闲还是开台）
				picture.setTime(cursor.getString(cursor
						.getColumnIndex("iTabletime")));	//开台的时间			
				picture.setNumber(cursor.getString(cursor
						.getColumnIndex("iTableNumber")));	//台号
				picture.setTablePlace(cursor.getString(cursor
						.getColumnIndex("iTableClass")));	//桌台类型（大厅还是包厢）
				picture.setTablePersonNumber(cursor.getString(cursor
						.getColumnIndex("iTablePerson")));	//可容纳人数
				picture.setTable_PersonNumber(cursor.getString(cursor
						.getColumnIndex("iTable_Person")));	//可容纳人数

				mylist.add(picture);
			}
			NOWPAGE.setText(""+pageID);
			if (pageID == 1)
				ALLPAGE.setText(   String.valueOf( cursor.getCount()/30 + 1 )   );
			cursor.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

		adapterr = new GridItemTableSQLAdapter(mylist, this , Dispay_widthPixels);// 自定义适配器
		GRIDVIEW_TABLE.setAdapter(adapterr);
	}

	private void key_things() {
		// TODO Auto-generated method stub
		 GRIDVIEW_TABLE.setOnItemClickListener(new OnItemClickListener()   
         {   
             public void onItemClick(AdapterView<?> parent, View v, int position, long id)   
             {   
                 NEW_Table_Num 	=	mylist.get(position).getNumber();
                 String new_Table_State	=	mylist.get(position).getSringTableState();
                 Integer intObj = new Integer( new_Table_State );
			   	 int i = intObj.intValue();
			   	 
			   	 //根据桌台状态判断
			   	 
			   	 //如果已经开过台的就不运行，只提示该台已经开台了
			   	 if (i == 1) {
	            	 //启动一个对话框，询问是否确定
	                 showDialog(DIALOG_FIND);

	            	 //确定!就把该新的桌台和开台单号绑定
			   		 
			   		 //不确定，就关闭对话框
			   	 } else {
	                 Toast.makeText(Table_ZhuanTai.this, "该台已经开台", Toast.LENGTH_SHORT).show();

	                 
			   	 }  

             }  
         });     
		 
			FRONTPAGE.setOnClickListener(new Button.OnClickListener()
		    {
			   	@Override
			   	public void onClick(View v)
			   	{	
			   		Integer intObj = new Integer( NOWPAGE.getText().toString() );
			   	    int i = intObj.intValue();	
			   	    if(i == 1)
			   	    {
			   	    	Toast.makeText(Table_ZhuanTai.this, "已经是最前一页了", Toast.LENGTH_SHORT).show();
			   	    }
			   	    else
			   	    {	
			   	    	init_grid( i-1);
			   	    	NOWPAGE.setText(""+(i-1));
			   	    	nowpage = i-1;
			   	    }	
			   	}
		    });	
			NEXTPAGE.setOnClickListener(new Button.OnClickListener()
		    {
			   	@Override
			   	public void onClick(View v)
			   	{	
			   		Integer intObj = new Integer( NOWPAGE.getText().toString() );
			   	    int i = intObj.intValue();	

			   		intObj = new Integer( ALLPAGE.getText().toString() );
			   	    int j = intObj.intValue();	
			   	    
			   	    if(i == j)
			   	    {
			   	    	Toast.makeText(Table_ZhuanTai.this, "已经是最后一页了", Toast.LENGTH_SHORT).show();
			   	    }
			   	    else
			   	    {	
			   	    	init_grid( i+1);
			   	    	NOWPAGE.setText(""+(i+1));
			   	    	nowpage = i+1;
			   	    }				   	 
			   	}
		    });	
	}
	
	protected void RefreshGrid(String SQL_String , String[] Sql_String_condition) {
		// TODO Auto-generated method stub
		// 用于初始化
//		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);
		mylist = new ArrayList<Grid_Item_Table>();

		try {
    		Cursor  cursor = db.rawQuery(SQL_String, Sql_String_condition);
			while (cursor.moveToNext()) {
				Grid_Item_Table picture = new Grid_Item_Table();
				picture.setImageId(cursor.getInt(cursor
						.getColumnIndex("iTableState")));
				picture.setTableState(cursor.getString(cursor
						.getColumnIndex("iTableState")));	//桌台的状态（空闲还是开台）
				picture.setTime(cursor.getString(cursor
						.getColumnIndex("iTabletime")));	//开台的时间			
				picture.setNumber(cursor.getString(cursor
						.getColumnIndex("iTableNumber")));	//台号
				picture.setTablePlace(cursor.getString(cursor
						.getColumnIndex("iTableClass")));	//桌台类型（大厅还是包厢）
				picture.setTablePersonNumber(cursor.getString(cursor
						.getColumnIndex("iTablePerson")));	//可容纳人数
				picture.setTable_PersonNumber(cursor.getString(cursor
						.getColumnIndex("iTable_Person")));	//可容纳人数

				mylist.add(picture);
			}
			cursor.close();
		} catch (Exception e) {
			// TODO: handle exception
		}

		adapterr = new GridItemTableSQLAdapter(mylist, this , Dispay_widthPixels);// 自定义适配器
		GRIDVIEW_TABLE.setAdapter(adapterr);		
	}

	private void find_id() {
		// TODO Auto-generated method stub
		GRIDVIEW_TABLE	= (GridView) findViewById(id.all_tables);
		ALL_TABLE 		= (TextView) findViewById(id.table_all);
		ALL_FREE_TABLE	= (TextView) findViewById(id.table_free);
		FRONTPAGE		= (Button) 	 findViewById(id.table_page_front);
		NEXTPAGE		= (Button) 	 findViewById(id.table_page_next);
		NOWPAGE			= (TextView) findViewById(id.table_page_now);
		ALLPAGE			= (TextView) findViewById(id.table_page_all);
	}

	
	
	/***      初始一个对话框！ 命名为buildDialog      ***/
    private Dialog buildDialog(Context context) {
		// TODO Auto-generated method stub
        final AlertDialog.Builder builder =   new AlertDialog.Builder(context);  
        //下面是设置对话框的属性
        builder.setIcon(R.drawable.other_1);  
        builder.setTitle("转台操作");  
        LayoutInflater inflater = LayoutInflater.from(Table_ZhuanTai.this);
        View view = null ;
        ref_if = false;

        switch (Dispay_widthPixels) {
			case 1024:
		        view = inflater.inflate(R.layout.i800dialog_table_zhuantai, null);			
				break;
			case 800:
		        view = inflater.inflate(R.layout.i800dialog_table_zhuantai, null);			
				break;
			default:
		        view = inflater.inflate(R.layout.i800dialog_table_zhuantai, null);			
				break;
		}
        builder.setView(view);
        builder.setCancelable(false);
        
        
		DAILOG_BTN_SURE		= (Button) view.findViewById(id.diglog_table_sure);
		DAILOG_BTN_CANCEL	= (Button) view.findViewById(id.diglog_table_cancel);
		
		DAILOG_TEXT_TABLE_OLD_NUM = (TextView) view.findViewById(id.diglog_table_old_number);
		DAILOG_TEXT_TABLE_NUM = (TextView) view.findViewById(id.diglog_table_number);
		DAILOG_TEXT_TABLE_SELLNUM = (TextView) view.findViewById(id.diglog_table_sellnumber);

		DAILOG_TEXT_TABLE_OLD_NUM.setText(Share_Table_Num);
		DAILOG_TEXT_TABLE_NUM.setText(NEW_Table_Num );
		DAILOG_TEXT_TABLE_SELLNUM.setText(Share_Table_SELLNum);
		 
		DAILOG_BTN_SURE.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{   		
		   		//试验代码开始
		   		//获取当前桌台的开台单号
		   		String this_tableNum 	 = DAILOG_TEXT_TABLE_NUM.getText().toString();
		   		String this_tableSellNum = DAILOG_TEXT_TABLE_SELLNUM.getText().toString();

		   		//获取旧台相关信息
		   		
		   		//复制到新桌台 
		   		//设置用餐人数
		   		String person_num	=	"4"; //DAILOG_TEXT_PERSON_NUM.getText().toString();
		   		if(person_num.equals("") || person_num == null  || person_num.equals("0"))
		   		{//会抛出异常
		   			Toast.makeText(Table_ZhuanTai.this, "开台人数不能为空", Toast.LENGTH_LONG).show();
		   		}
		   		else
		   		{	
			   		// 根据桌台号 和 日期合并  生成销售单号
	//		   		String Sell_Number	=	person_num+mYear+mMonth+mDay+mHour+mMinute;
			   		//开台
			   		ContentValues cv = new ContentValues();
				   	//存储修改的数据
				   	cv.put("iTableState" ,2);
				   	cv.put("iTable_Person",person_num);
//				   	cv.put("iTabletime",mHour+":"+mMinute);
				   	String[] contion = {NEW_Table_Num}; 
			   		try {
					   	//更新数据
					   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
					} catch (Exception e) {
						// TODO: handle exception
					}
		   		}
		   		
		   		//修改数据库，把当前台信息同步到15号台
		   		try {
				   	//更新数据
				   	db.execSQL("insert into lfcy_base_opentableinf values(?,?)", 
							new String[]{
				   			NEW_Table_Num , this_tableSellNum});
				} catch (Exception e) {
					// TODO: handle exception
				}
				
		        init_grid(1);
		        Refresh_State();
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		        ref_if = true;		   		
		        
		        
		        //把旧台清除干净
		   		ContentValues cv = new ContentValues();
			   	//存储修改的数据
			   	cv.put("iTableState" ,1);
			   	cv.put("iTable_Person","");
			   	cv.put("iTabletime","");
			   	String[] contion = {Share_Table_Num}; 
		   		try {
				   	//更新数据
				   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
				} catch (Exception e) {
					// TODO: handle exception
				}
		        
		        
		        //试验代码结束
		   			   		
		   		
		   		//返回
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   		finish();
		        ref_if = true;
		   	}
	    });
		
		DAILOG_BTN_CANCEL.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		//返回
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		        ref_if = true;
		   	}
	    });
		
        return builder.create();  
    } 
    
	@Override 
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
        if(id==101){  
        	return this.buildDialog(Table_ZhuanTai.this);  
        }
        else{  
            return null;  
        }  
    } 

    @Override 
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(DIALOG_FIND, dialog);  
    } 
    /***      以上是初始一个对话框！       ***/	
    
    /**************以下是对Activity生命周期的相关****************************/
	@Override  
    protected void onRestoreInstanceState(Bundle savedInstanceState) {  
        // TODO Auto-generated method stub  
        super.onRestoreInstanceState(savedInstanceState);  
        Log.i("info", "onRestoreInstanceState");  
    }  
      
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        // TODO Auto-generated method stub  
        super.onActivityResult(requestCode, resultCode, data);  
        Log.i("info", "onActivityResult");  
    }  
      
    @Override  
    protected void onSaveInstanceState(Bundle outState) {  
        // TODO Auto-generated method stub  
        super.onSaveInstanceState(outState);  
        Log.i("info", "onSaveInstanceState");  
    }  
      
    @Override  
    protected void onStart() {  
        // TODO Auto-generated method stub  
        super.onStart();  
        Log.i("info", "onStart");  
    }  
  
    @Override  
    protected void onRestart() {  
        // TODO Auto-generated method stub  
        super.onRestart();  
        Log.i("info", "onRestart");  
    }  
  
 
    @Override  
    protected void onPause() {  
        // TODO Auto-generated method stub  
        super.onPause();  
        ref_if = false;
        Log.i("info", "onPause");  
    }  
  
    @Override  
    protected void onStop() {  
        // TODO Auto-generated method stub  
        super.onStop();  
        ref_if = false;
        Log.i("info", "onStop");  
    }  
  
    @Override  
    protected void onDestroy() {  
        // TODO Auto-generated method stub  
        super.onDestroy();  
        Log.i("info", "onDestroy");  
    }  
  
    @Override  
    public void onLowMemory() {  
        // TODO Auto-generated method stub  
        super.onLowMemory();  
        //当系统内存不足时 才会调用  但不一定会百分百调用  如果能及时调用则会调用  可能在没用调用之前就将程序关闭了。  
        Log.i("info", "onLowMemory");  
    }  
  
    @Override  
    public void onBackPressed() {  
        // TODO Auto-generated method stub  
        super.onBackPressed();  
        
        ref_if = false;
        Log.i("info", "onBackPressed");  
        //  
    }  
  
    @Override  
    public void finish() {  
        // TODO Auto-generated method stub  
        super.finish();  
        //要关闭Activity 所以才要调用finish()方法  
        ref_if = false;
        Log.i("info", "finish");  
    }  
    /**************以上是对Activity生命周期的相关****************************/
   
}